package com.yuzi.model.BaseMo;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public abstract class BaseModel<M extends Model<M>> extends Model<M>{
    private static Map<Class<? extends BaseModel> ,BaseModel> INSTANCE_MAP = new HashMap<>();

    /**
     * 存取实例化的Model
     * @param clazz
     * @param <Mo>
     * @return
     */
    public static <Mo extends BaseModel> Mo getInstance(Class<Mo> clazz){
        Mo model = (Mo)INSTANCE_MAP.get(clazz);
        if (model == null){
            try{
                model = clazz.newInstance();
                INSTANCE_MAP.put(clazz, model);
            }catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return model;
    }

    /**
     * 默认通过获取
     * @param baseModel
     * @return
     */
    public int getMaxIndex(BaseModel baseModel){
        Model model = getMaxIndexModel(baseModel);
        if (model == null){
            return 0;
        }
        return model.getInt("id");
    }

    public Model getMaxIndexModel(BaseModel baseModel){
        Table tableInfo = TableMapping.me().getTable(baseModel.getClass());
        String sql = "select * from "+ tableInfo.getName() + " order by id desc limit 0,1 ";
        List<M> modelList = this.find(sql);
        if (modelList!=null && modelList.size() > 0){
            return modelList.get(0);
        }else{
            return null;
        }
    }
}
